package com.javaweb.util.core;

import java.io.InputStream;

import org.apache.pdfbox.io.RandomAccessRead;
import org.apache.pdfbox.io.RandomAccessReadBuffer;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;

import com.javaweb.constant.CommonConstant;

public class PdfUtil {

	/** 只支持文档型的pdf，不支持图片型的pdf，图片型需要如下处理：
    <dependency>
		<groupId>net.sourceforge.tess4j</groupId>
		<artifactId>tess4j</artifactId>
		<version>4.3.1</version>
	</dependency>
	//pdf转图片
	File file = new File("D:\\桌面\\1.pdf");
	PDDocument doc = PDDocument.load(file);
	PDFRenderer renderer = new PDFRenderer(doc);
	PDPageTree pages = doc.getPages();
	int pageCount = pages.getCount();
	for(int i=0;i<pageCount;i++){
		BufferedImage image = renderer.renderImageWithDPI(i,200);
		ImageIO.write(image, "JPEG", new File("D:\\桌面\\"+i+".jpeg"));
	}
	doc.close();
	//识别图片
	ITesseract instance = new Tesseract();
	instance.setDatapath("tessdata");
	instance.setLanguage("chi_sim");
	instance.setTessVariable("tessedit_create_pdf", "1");
	instance.setTessVariable("tessedit_pageseg_mode", "1");
	String result = instance.doOCR(new File("D:\\桌面\\0.jpeg"));
	System.out.println(result);
	注：需要在项目根目录下新建一个文件夹，这里为tessdata，然后将训练集，如chi_sim.traineddata放在里面，可能还需要一个osd.traineddata
	*/
	public static String readPdf(InputStream inputStream) {
		String out = CommonConstant.NULL_VALUE;
		try {
			//RandomAccessBuffer buffer = new RandomAccessBuffer(inputStream);
			RandomAccessRead buffer = new RandomAccessReadBuffer(inputStream);
			PDFParser pdfParser = new PDFParser(buffer);
			pdfParser.parse();
			//PDDocument document = pdfParser.getPDDocument();
			PDDocument document = pdfParser.parse();
			//获取页码
			int pages = document.getNumberOfPages();
			PDFTextStripper stripper = new PDFTextStripper();
			//设置按顺序输出
			stripper.setSortByPosition(true);
			stripper.setStartPage(1);
			stripper.setEndPage(pages);
			out = stripper.getText(document);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return out;
	}

}
